import PrinterJobs from './common/print/printerjobs.js'
import printerUtil from './common/print/printerutil.js'
import util from './common/print/util.js'
import drawQrcode from './common/print/weapp.qrcode.esm.js'
import Bluetooth from './common/print/bluetooth.js'

let bluetooth = new Bluetooth();

var a = getApp();

a.bluetooth = bluetooth;

var base = require('../../../utils/lang.js');
const _ = base._

Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: base._t(),
    isServerOpen:false,
    isOpenBle: false, //是否已经打开蓝牙，默认为false
    devicesList: [], //设备列表
    serviceList: [], //服务列表
    deviceId: "", //选中的deviceId
    canvas_width: 240,
    canvas_height: 240,
  },

  //搜索周边设备
  async startBluetoothDeviceDiscovery() {
    wx.closeBluetoothAdapter({
      success (res) {
        console.log('断开蓝牙连接')
        console.log(res)
      }
    })
    let _isOpenBle = await bluetooth.openBluetoothAdapter();

    console.log('开启蓝牙连接')
    console.log(_isOpenBle)

    
    if(_isOpenBle.errMsg!=="openBluetoothAdapter:ok"){
      return
    }

    wx.showLoading({
      title: _('蓝牙搜索中')
    })
    setTimeout(() => {
      wx.startBluetoothDevicesDiscovery({
        success: res => {
          wx.hideLoading();
          wx.onBluetoothDeviceFound(devices => {
            console.log("发现设备: " + JSON.stringify(devices));
            let { devicesList } = this.data
            //不重复,就添加到devicesList中,
            if (!devicesList.some(item => {
                return item.deviceId === devices.devices[0].deviceId
              })) {
              console.log(devices.devices)
              devicesList.push(devices.devices[0])
            }
            this.setData({ devicesList })
          });
        },
        fail: res => {
          wx.hideLoading();
          self.showToast(_('搜索设备失败') + JSON.stringify(err));
        }
      })
    }, 200)
  },

  //停止搜索蓝牙设备
  stopBluetoothDevicesDiscovery() {
    wx.hideLoading();
    bluetooth.stopBluetoothDevicesDiscovery();
  },


  //选中设备
  async select_deviceId(e) {
    let { item } = e.currentTarget.dataset
    this.setData({
      deviceId:item.deviceId
    })
    bluetooth.deviceId = item.deviceId;
    wx.setStorageSync('deviceId', bluetooth.deviceId);

    try {
      //1.链接设备
      let result = await bluetooth.createBLEConnection();
      //2.寻找服务
      let result2 = await bluetooth.getBLEDeviceServices();

      console.log("获取服务: " + JSON.stringify(result2));

      this.setData({
        serviceList:result2
      })

    } catch (e) {
      //TODO handle the exception
      console.log("e: " + JSON.stringify(e));
    }
  },

  //选中服务
  async select_service(e) {
    let res =  e.currentTarget.dataset.item
    bluetooth.serviceId = res.uuid;
    wx.setStorageSync('serviceId', res.uuid);
    try {
      let result = await bluetooth.getBLEDeviceCharacteristics();
      // console.log(result)
      if(result){
        wx.showToast({
          title: _('打印机连接成功'),
          icon: 'none',
          'duration': 2000
        })

        setTimeout(()=>{
          wx.navigateTo({
            url: '../wmdd/wmdd',
          });
        },1000)
      }

    } catch (e) {
      //TODO handle the exception
      console.log("e: " + JSON.stringify(e));
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	  const isWei = base.isWeiFn()
	  this.setData({ isWei }) 
    const _deviceId = wx.getStorageSync('deviceId');
    const _serviceId = wx.getStorageSync('serviceId');
    const _notifyId = wx.getStorageSync('notifyId');
    const _writeId = wx.getStorageSync('writeId');
      
    console.log('_deviceId:'+_deviceId)

    if(_deviceId && _serviceId && _notifyId && _writeId){
      this.setData({ isServerOpen:true })
    }

    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        console.log('当前位置的经度：' + res.longitude);
        console.log('当前位置的纬度：' + res.latitude);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
this.setData({ _t: base._t() })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})